/**
 * Created by zoushuiyun on 2017/3/3.
 */
import {
  Component, OnInit, ComponentFactoryResolver, ChangeDetectionStrategy, ViewChild,
  AfterViewChecked} from "@angular/core";
import {ModalService, DialogService, OverlayService} from "rebirth-ng";
import {Router, ActivatedRoute} from "@angular/router";
import "rxjs/add/operator/filter";
import {FormGroup, NgForm} from "@angular/forms";
import {TestModalContentComponent} from "../../shared/modals/demo-modal/test-modal-content.component";
const now = new Date();
@Component({
  selector: 'rebirth-demo',
  templateUrl: 'rebirth-demo.component.html',
  providers: [],
  changeDetection: ChangeDetectionStrategy.OnPush,
  styleUrls:['rebirth-demo.component.scss']
})
export class RebirthDemoComponent implements OnInit,AfterViewChecked {
  dataForm: NgForm
  formDataObj:any={}
  formErrors:any={}
  @ViewChild('dataForm') currentForm: NgForm;
  onSubmitTag(dataForm: FormGroup){
    console.log(dataForm)
    if (dataForm.valid) {
      console.log("form is ok============")
    } else{
      console.error("form error============")
    }
  }
  date: {year: number, month: number};
model:any
  selectToday() {
    this.model = {year: now.getFullYear(), month: now.getMonth() + 1, day: now.getDate()};
  }
  toTag(){
    this.formDataObj.tag = this.formDataObj.single
  }

  ngAfterViewChecked() {
    this.formChanged();
  }
  formChanged() {
    if (this.currentForm === this.dataForm) { return; }
    this.dataForm = this.currentForm;
    if (this.dataForm) {
      this.dataForm.valueChanges
        .subscribe(data => this.onValueChanged(data));
    }
  }
  onValueChanged(data?: any) {
    // console.log(data)
    if (!this.dataForm) { return; }
    const form = this.dataForm.form;
    for(const field in data){
      this.formErrors[field] = '';
      const control = form.get(field);

      if (control && control.dirty && !control.valid) {
        // const messages = this.validationMessages[field];
        for (const key in control.errors) {
          // console.log(field)
          // console.log(key)
          // console.log(control)
          if(key=="myNewTag"){
            this.formErrors[field] += control.errors[key].tip + ' ';
          }else if(key=="myTag"){
            this.formErrors[field] += control.errors[key].tip + ' ';
          }else if(key=="required"){
            this.formErrors[field] += '不能为空 ';
          }else if(key=="minlength"){
            this.formErrors[field] += '最少要有'+control.errors[key].requiredLength+'子字符';
          }else if(key=="maxlength"){
            this.formErrors[field] += '';
          }else {//TODO 编辑各种错误提示
            this.formErrors[field] += key + ' ';
          }
        }
      }
    }
  }







  momentValue:any= "2017-01-11 06:05"

  dateTo:any;
  doSomething(event,key){
    console.log(this.momentValue)
    console.log(event)
     let d = new Date(event)
    console.log(d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate() + ' ' + d.getHours() + ':' + d.getMinutes())
    console.log(typeof event)
    console.log(key)
    console.log(this.dateTo)
  }
  selectDate(id){
    document.getElementById(id).focus()
  }
  // myOptions: KalendarOptions = {
  //   format: 'yyyy-mm-dd H:MM',
  //   showTimepicker: true
  // }
  a2eOptions: any;
  data:any;
  dateChange(date) {
    this.dateTo = date;
  }

  dateClick() {
    console.log('click click!')
  }


  title: any
  text = 88
  pager = {
    total: 306,
    pageIndex: 5,
    pageSize: 10
  };

  /**
   * 构造函数
   * @param checkService
   */
  constructor(private router: Router, private route: ActivatedRoute, private modalService: ModalService, private dialogService: DialogService,
              private  overlayService: OverlayService,
              private componentFactoryResolver: ComponentFactoryResolver) {
    console.log(window.location);
    // router.events
    //   .subscribe(route  => {
    //     console.log(route);
    //   });
    // var client = new OSS.Wrapper({
    //   region: 'oss-cn-shanghai',
    //   accessKeyId: 'V6x1Xu1p0PxZVJtP',
    //   accessKeySecret: 'nGF9upSrDGWbB220WmP7rmeure1BGz',
    //   bucket: 'video-upload-test'
    // });
    // client.list({
    //   'max-keys': 5
    // }).then(function (result) {
    //   console.log(result);
    // }).catch(function (err) {
    //   console.log(err);
    // });
  }

  ngOnInit(): void {
    this.data = {};
    console.log("第2步应该ngOnInit模板 =====2222222")
    this.title = "rebirth-UI使用例子参考"
    this.dateFormat = this.dateFormatOptions[0];
    // console.log(this.cacheService.getHtmlTest())
  }

  setSelection(input, selectionStart, selectionEnd) {

    // if (input.setSelectionRange) {
    //   input.focus();
    //   input.setSelectionRange(selectionStart, selectionEnd);
    // } else if (input.createTextRange) {
    //   var range = input.createTextRange();
    //   range.collapse(true);
    //   range.moveEnd('character', selectionEnd);
    //   range.moveStart('character', selectionStart);
    //   range.select();
    // }
    let  caretPos = input.selectionStart;
    console.log(caretPos)
    let text= input.value = input.value.substring(0,caretPos)+"==="+input.value.substring(caretPos)
    let find_string="===";
    let j=find_string.length;
    let len=text.length;
    console.log(input)
    input.focus()
    for(let i=caretPos;i<len-j;i++) {
      var son_string = text.substring(i, i + j);
      if (son_string == find_string) {
        console.log(input.setSelectionRange)
        if (input.setSelectionRange) {
          input.setSelectionRange(i, i + j);
        }//ff
        else {//ie
          var range = input.createTextRange();
          range.collapse(true);
          range.moveStart('character', i);
          range.moveEnd('character', j);
          range.select();
        }
        break;
      }
    }
  }
  selectAllContent($event) {
    console.log($event)
    $event.target.select("===");
  }


  pageChange(pageIndex) {
    console.log(`Rebirth pager change to: ${pageIndex}`, this.pager);
  }

  dateFormatOptions = ['YYYY-MM-DD HH:mm', 'YY-MM-DD HH:mm', 'MM/DD/YYYY HH:mm', 'MM/DD/YY HH:mm'];
  dateFormat: string;
  selectedDate1: Date;
  selectedDate2: Date;
  selectedDate3 = new Date('01/02/2017 09:11');


  /*Confirm对话框例子*/
  confirm() {
    this.dialogService.confirm({
      title: "标题",
      content: "内容",
      yes: '确定',
      no: '取消',
      cssClass: '.btn-primary{  color: #c12b5b;}',
      html: true
    })
      .subscribe(
        data => this.afterConfirm(true, data),
        error => this.afterConfirm(false, error)
      );

  }

  afterConfirm(status, param) {
    this.overlayService.open({html: `<div class="overlay-demo-logo" style="  width: 330px;height: 360px;background: url('../../../assets/images/loading.gif');"></div>`});
    console.log(status)
    console.log("调用confirm对话框确认返回执行方法======================status")
    console.log(param)
    setTimeout(() => this.overlayService.close(), 1 * 1000);
  }

  /*模态窗口例子*/
  openModal() {
    this.modalService.open<string>({
      component: TestModalContentComponent,
      componentFactoryResolver: this.componentFactoryResolver,
      resolve: {
        text: 'I am from resolve data!',
        param1: 232,
        param2: "参数2"
      }
    })
      .subscribe(data => {
        console.log('一级窗口成功回调事件', data);
      }, error => {
        console.error('一级窗口失败回调事件', error);
      });
  }

  ids:any = ",form1,"
  showOrHidden(text){
    return(this.ids.indexOf(text) > -1)
  }



}



